//
//  COLoginIndexViewController.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/17.
//

import UIKit
import QMUIKit
import SnapKit
import RZColorfulSwift
import SwifterSwift
import AuthenticationServices
import HDeviceIdentifier

class COLoginIndexViewController: COBaseViewController {
    override var navShow: Bool {
        false
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        
    }
    
    override func configUI() {
        view.backgroundColor = .rgba(17, 7, 41)
        
        view.addSubview(logo)
        view.addSubview(nameLabel)
        view.addSubview(userLoginButton)
        view.addSubview(signInButton)
        view.addSubview(appleButton)
        view.addSubview(signUpButton)
        view.addSubview(delegateLabel)
        
        logo.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight+106)
            make.width.height.equalTo(110)
        }
        
        nameLabel.snp.makeConstraints { make in
            make.top.equalTo(logo.snp.bottom).offset(10)
            make.centerX.equalToSuperview()
        }
        
        userLoginButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(19)
            make.bottom.equalTo(signUpButton.snp.top).offset(-20)
            make.height.equalTo(50)
        }
        
        signUpButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(19)
            make.top.equalTo(nameLabel.snp.bottom).offset(120)
            make.height.equalTo(50)
        }
        
        appleButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(19)
            make.top.equalTo(signUpButton.snp.bottom).offset(20)
            make.height.equalTo(50)
        }
        
        signInButton.snp.makeConstraints { make in
            make.top.equalTo(appleButton.snp.bottom).offset(25)
            make.centerX.equalToSuperview()
        }
        
        delegateLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-bottomSafeHeight-41)
        }
    }

    
    private lazy var logo: UIImageView = {
        let imgV = UIImageView(image: UIImage(named: "logo"))
        return imgV
    }()
    
    private lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = .bold(41)
        label.textColor = .white
        label.text = "TAGI"
        return label
    }()
    
    private lazy var userLoginButton: UIButton = {
        let btn = UIButton()
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor.rgba(218, 67, 255).cgColor, UIColor.rgba(82, 28, 255).cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = CGRect(x: 0, y: 0, width: SCREENWIDTH-38, height: 50)
        bgLayer1.startPoint = CGPoint(x: 1, y: 0.56)
        bgLayer1.endPoint = CGPoint(x: 0.56, y: 0.56)
        btn.layer.insertSublayer(bgLayer1, at: 0)
        
        btn.setTitle("I'm browsing as a visitor", for: .normal)
        btn.titleLabel?.font = .medium(14)
        btn.setTitleColor(.white, for: .normal)
        
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 25
        
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)

        return btn
    }()
    
    private lazy var signUpButton: UIButton = {
        let btn = UIButton()
        
        btn.setTitle("Sign Up", for: .normal)
        btn.titleLabel?.font = .medium(14)
        btn.setTitleColor(.white, for: .normal)
        
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 25
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.rgba(218, 67, 255, 1).cgColor
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)

        return btn
    }()
    
    private lazy var appleButton: QMUIButton = {
        let btn = QMUIButton()
        btn.imagePosition = .left
        btn.spacingBetweenImageAndTitle = 3.5
        btn.setTitle("Sign in with Apple", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .medium(14)
        btn.setImage(UIImage.init(named: "苹果"), for: .normal)
        btn.tintColor = .white
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 25
        btn.layer.borderWidth = 1.5
        btn.layer.borderColor = UIColor.white.cgColor
        
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)

        return btn
    }()
    
    private lazy var signInButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("Sign in", for: .normal)
        btn.setTitleColor(.rgba(255, 255, 255, 0.5), for: .normal)
        btn.titleLabel?.font = .medium(14)
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
    
    private lazy var delegateLabel: UILabel = {
        let label = UILabel()
        label.rz.colorfulConfer { confer in
            confer.text("Agree to the ")?.font(.regular(12)).textColor(.white)
            confer.text("Terms of Service")?.font(.regular(12)).textColor(.rgba(152, 48, 255)).tapAction("term")
            confer.text(" and ")?.font(.regular(12)).textColor(.white)
            confer.text("Privacy Policy")?.font(.regular(12)).textColor(.rgba(255, 148, 31)).tapActionByLable("privacy")
        }
        
        label.rz.tapAction {[weak self] label, tapActionId, range in
            var url = ""
            if tapActionId == "term" {
                url = KTerms
            } else if tapActionId == "privacy" {
                url = KPolicy
            }
            
            let vc = COWebViewController(url)
            self?.navigationController?.pushViewController(vc)
        }
        
        return label

    }()
}

extension COLoginIndexViewController {
    @objc
    private func clickButton(_ btn: UIButton) {
        if btn == signInButton {
            let vc = COSignInViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        } else if btn == signUpButton {
            let vc = COSignUpViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        } else if btn == appleButton {
            self.loginWithApple()
        } else if btn == userLoginButton {
            self.oneLogin()
        }
    }
}

extension COLoginIndexViewController: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    private func loginWithApple() {
        let provider = ASAuthorizationAppleIDProvider()
        let request = provider.createRequest()
        var requests: [ASAuthorizationRequest] = []
        requests.append(request)
        
        let authController = ASAuthorizationController(authorizationRequests: requests)
        authController.delegate = self
        authController.presentationContextProvider = self
        authController.performRequests()
    }
    
    @available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let cred = authorization.credential as? ASAuthorizationAppleIDCredential {
            let userId = cred.user
//            self.toRegister(userId)
            CONetwork.sendRequest(provider: loginProvider, target: .apple(code: userId)) { text in
                guard let userInfo = COUserInfo.deserialize(from: text.dic) else {
                    return
                }
                
                COUserManager.userInfo = userInfo
                self.updateMessage()
            } failedBlock: { _, text in
                self.view.hideToastActivity()
                self.view.makeToast(text, position: .center)
            }

            
            return
        } else {
            self.view.hideToastActivity()
            self.view.makeToast("Login failed", duration: 2, position: .center)
        }
        
    }
    
    @available(iOS 13.0, *)
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        let err = error as NSError
        let errType = ASAuthorizationError.Code(rawValue: err.code) ?? .canceled
        // 授权失败
        switch errType {
        case .canceled:
            debugPrint("Revoke")
        case .failed:
            self.view.makeToast("Authorization request failed", duration: 2, position: .center)
        case .invalidResponse:
            self.view.makeToast("Invalid authorization request response", duration: 2, position: .center)
        case .notHandled:
            self.view.makeToast("Failed to process authorization request", duration: 2, position: .center)
        default:
            self.view.makeToast("An unknown error occurred in the authorization request", duration: 2, position: .center)
        }
    }
    
    @available(iOS 13.0, *)
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.view.window ?? UIWindow()
    }
    
    private func updateMessage() {
        CONetwork.sendRequest(provider: loginProvider, target: .mine) { text in
            self.view.hideToastActivity()
            guard let userInfo = COUserInfo.deserialize(from: text) else {
                return
            }
            userInfo.token = COUserManager.userInfo?.token ?? ""
            COUserManager.userInfo = userInfo
            let vc = COHomeViewController()
            self.navigationController?.setViewControllers([vc], animated: true)
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }
    }
}

extension COLoginIndexViewController {
    private func oneLogin() {
        self.view.makeToastActivity(.center)
        let uuid = HDeviceIdentifier.deviceIdentifier() ?? ""
        CONetwork.sendRequest(provider: loginProvider, target: .userLogin(loginCode: uuid)) { text in
            self.view.hideToastActivity()
            guard let userInfo = COUserInfo.deserialize(from: text.dic) else {
                return
            }
            COUserManager.userInfo = userInfo
            self.updateMessage()
        } failedBlock: { _, text in
            self.view.hideToastActivity()
            self.view.makeToast(text, position: .center)
        }
    }
}

